package cn.com.joycode.nimble.opencv.test.opencv;

import cn.com.joycode.nimble.opencv.test.BaseTest;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.bytedeco.javacv.OpenCVFrameConverter;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferByte;
import java.io.File;

@Slf4j
public class OpenCVImageRead extends BaseTest {

    @BeforeAll
    public static void before() {
        //System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    }


    @Test
    public void imreadTest2() throws Exception {
        String filepath = ResourceUtil.getResource("images/douyin/samples/540/0002.png").getPath();
        filepath = StrUtil.removePrefix(filepath, "/");
        log.info("读取文件:{}", filepath);
        org.opencv.core.Mat mat = Imgcodecs.imread(filepath);
        HighGui.imshow("中文的", mat);
        HighGui.waitKey();
    }

    /**
     * opencv 读取中文路径并显示
     */
    @Test
    public void imreadTest4() throws Exception {
        String filepath = URLUtil.decode(ResourceUtil.getResource("images/douyin/samples/中文测试.png").getPath());
        filepath = StrUtil.removePrefix(filepath, "/");
        log.info("读取文件:{}", filepath);
        BufferedImage bufferedImage = ImageIO.read(new File(filepath));
        byte[] pixels = ((DataBufferByte) bufferedImage.getRaster().getDataBuffer()).getData();
        org.opencv.core.Mat mat = new org.opencv.core.Mat(bufferedImage.getHeight(), bufferedImage.getWidth(), CvType.CV_8UC3);
        mat.put(0, 0, pixels);
        HighGui.imshow("中文的", mat);
        HighGui.waitKey();
    }

    @Test
    public void imreadTest5() throws Exception {
        String filepath = URLUtil.decode(ResourceUtil.getResource("images/douyin/samples/中文测试.png").getPath());
        log.info("读取文件:{}", filepath);
        BufferedImage bufferedImage = ImageIO.read(new File(filepath));
        OpenCVFrameConverter.ToMat converter1 = new OpenCVFrameConverter.ToMat();
        OpenCVFrameConverter.ToOrgOpenCvCoreMat converter2 = new OpenCVFrameConverter.ToOrgOpenCvCoreMat();
        Java2DFrameConverter java2DConverter = new Java2DFrameConverter();
        Frame frame = java2DConverter.convert(bufferedImage);
        org.bytedeco.opencv.opencv_core.Mat mat1 = converter1.convert(frame);
        Mat mat2 = converter2.convert(converter1.convert(mat1));
        HighGui.imshow("中文的", mat2);
        HighGui.waitKey();
    }
}
